<template>
  <div class="table-recognizer">
    <h2>表格识别工具</h2>
    
    <!-- 主功能区域 -->
    <div class="main-content">
      <div 
        class="upload-zone"
        @drop.prevent="handleDrop"
        @dragover.prevent
        @dragenter.prevent
        @paste="handlePaste"
      >
        <div v-if="!selectedImage" class="upload-placeholder">
          <i class="upload-icon">📄</i>
          <p>拖拽含表格的图片到这里或点击上传</p>
          <input 
            type="file" 
            @change="handleFileSelect" 
            accept="image/*"
            class="file-input"
          >
        </div>
        
        <div v-else class="image-preview">
          <img 
            :src="previewUrl" 
            alt="预览图"
            @click="showPreview(previewUrl)"
          >
          <div class="image-info">
            <button @click="recognizeTable" class="recognize-btn">识别表格</button>
          </div>
        </div>
      </div>

      <div v-if="tableHtml" class="result-preview">
        <h3>识别结果预览</h3>
        <div class="table-wrapper" v-html="tableHtml"></div>
        <div class="export-buttons">
          <button @click="exportToExcel" class="export-btn">导出到Excel</button>
          <button @click="exportToWord" class="export-btn">导出到Word</button>
        </div>
      </div>
    </div>

    <!-- 功能说明区域 -->
    <div class="feature-intro">
      <details open>
        <summary>功能说明</summary>
        <div class="intro-content">
          <h3>功能简介</h3>
          <ul>
            <li>自动识别图片中的表格结构</li>
            <li>支持复杂表格布局</li>
            <li>支持中英文混合内容</li>
            <li>可导出为 Excel 或 Word 格式</li>
            <li>支持预览识别结果</li>
          </ul>
          
          <h3>使用说明</h3>
          <ul>
            <li>拖拽含表格的图片到上传区域，或点击上传</li>
            <li>直接粘贴截图（Ctrl+V）</li>
            <li>点击"识别表格"开始识别</li>
            <li>检查识别结果是否正确</li>
            <li>点击"导出到Excel"或"导出到Word"保存结果</li>
            <li>点击图片可放大预览</li>
          </ul>
          
          <div class="tips">
            <h3>使用技巧</h3>
            <ul>
              <li>确保图片清晰，表格线条完整</li>
              <li>避免表格倾斜或变形</li>
              <li>建议使用原图而不是截图</li>
              <li>表格周围留有适当空白</li>
            </ul>
          </div>
        </div>
      </details>
    </div>

    <!-- 预览弹窗 -->
    <div v-if="previewImage" class="preview-modal">
      <div class="preview-content">
        <img :src="previewImage" alt="预览图">
        <button class="close-btn" @click="previewImage = null">×</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'TableRecognizer',
  mounted() {
    // 添加全局粘贴事件监听
    document.addEventListener('paste', this.handlePaste)
  },
  beforeUnmount() {
    // 移除事件监听
    document.removeEventListener('paste', this.handlePaste)
  },
  data() {
    return {
      selectedImage: null,
      previewUrl: null,
      tableHtml: null,
      previewImage: null
    }
  },
  methods: {
    handleDrop(e) {
      const file = e.dataTransfer.files[0]
      if (file && file.type.startsWith('image/')) {
        this.handleImage(file)
      }
    },
    handleFileSelect(e) {
      const file = e.target.files[0]
      if (file) {
        this.handleImage(file)
      }
    },
    handleImage(file) {
      this.selectedImage = file
      this.previewUrl = URL.createObjectURL(file)
      this.tableHtml = null
    },
    async recognizeTable() {
      try {
        const formData = new FormData()
        formData.append('image', this.selectedImage)

        const response = await fetch('http://localhost:5000/api/recognize-table', {
          method: 'POST',
          body: formData
        })

        const result = await response.json()
        if (result.success) {
          this.tableHtml = result.html
        } else {
          alert('识别失败: ' + result.error)
        }
      } catch (error) {
        alert('识别过程出错: ' + error.message)
      }
    },
    async exportToExcel() {
      try {
        const response = await fetch('http://localhost:5000/api/export-excel', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ html: this.tableHtml })
        })
        
        const blob = await response.blob()
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = 'table.xlsx'
        a.click()
      } catch (error) {
        alert('导出失败: ' + error.message)
      }
    },
    async exportToWord() {
      try {
        const response = await fetch('http://localhost:5000/api/export-word', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ html: this.tableHtml })
        })
        
        const blob = await response.blob()
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = 'table.docx'
        a.click()
      } catch (error) {
        alert('导出失败: ' + error.message)
      }
    },
    showPreview(url) {
      this.previewImage = url
    },
    handlePaste(e) {
      const items = e.clipboardData.items
      for (let item of items) {
        if (item.type.indexOf('image') !== -1) {
          const file = item.getAsFile()
          this.handleImage(file)
          break
        }
      }
    }
  }
}
</script>

<style scoped>
.table-recognizer {
  max-width: 1000px;
  margin: 0 auto;
}

.upload-zone {
  border: 2px dashed #ccc;
  border-radius: 8px;
  padding: 40px;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.3s;
  margin-bottom: 20px;
}

.upload-zone:hover {
  border-color: #666;
}

.result-preview {
  margin-top: 30px;
}

.table-wrapper {
  overflow-x: auto;
  margin: 20px 0;
}

.recognize-btn, .export-btn {
  background-color: #4CAF50;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin: 10px;
}

.recognize-btn:hover, .export-btn:hover {
  background-color: #45a049;
}

.export-buttons {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.preview-content {
  position: relative;
  max-width: 90%;
  max-height: 90%;
}

.preview-content img {
  max-width: 100%;
  max-height: 90vh;
  object-fit: contain;
}

.close-btn {
  position: absolute;
  top: -40px;
  right: 0;
  background: none;
  border: none;
  color: white;
  font-size: 30px;
  cursor: pointer;
}

/* 添加鼠标指针样式 */
.image-preview img {
  cursor: pointer;
  transition: transform 0.2s;
}

.image-preview img:hover {
  transform: scale(1.02);
}

.feature-intro {
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.feature-intro details {
  background: #f5f5f5;
  border-radius: 8px;
  padding: 15px;
}

.feature-intro summary {
  cursor: pointer;
  font-weight: bold;
  color: #333;
  outline: none;
  padding: 5px;
}

.feature-intro summary:hover {
  color: #4CAF50;
}

.intro-content {
  padding: 15px 0;
}

.tips {
  margin-top: 15px;
  padding: 15px;
  background: #fff3e0;
  border-left: 4px solid #ff9800;
  border-radius: 4px;
}

.tips h3 {
  color: #f57c00;
}

.tips li::before {
  color: #ff9800;
}

.main-content {
  margin-bottom: 30px;
}
</style> 